"""
统一的条件表达式评估器
支持复杂的条件表达式，如：
- 简单比较：field == 0, field != 1, field > 5
- 范围：field in [0,1,2], field range [1,5]
- 逻辑运算：field == 0 || field == 1, field >= 0 && field <= 2
"""
from typing import Dict, Any
import re


class ConditionEvaluator:
    """条件表达式评估器"""

    @staticmethod
    def evaluate(condition: str, context: Dict[str, Any]) -> bool:
        """
        评估条件表达式

        Args:
            condition: 条件表达式字符串
            context: 上下文变量字典

        Returns:
            条件是否满足

        Examples:
            >>> evaluator = ConditionEvaluator()
            >>> evaluator.evaluate("count == 0", {"count": 0})
            True
            >>> evaluator.evaluate("count > 0 && count <= 5", {"count": 3})
            True
            >>> evaluator.evaluate("type in [1,2,3]", {"type": 2})
            True
        """
        condition = condition.strip()

        # 处理逻辑或
        if ' || ' in condition:
            sub_conditions = condition.split(' || ')
            return any(ConditionEvaluator.evaluate(sc.strip(), context)
                      for sc in sub_conditions)

        # 处理逻辑与
        if ' && ' in condition:
            sub_conditions = condition.split(' && ')
            return all(ConditionEvaluator.evaluate(sc.strip(), context)
                      for sc in sub_conditions)

        # 解析简单条件：field operator value
        return ConditionEvaluator._evaluate_simple(condition, context)

    @staticmethod
    def _evaluate_simple(condition: str, context: Dict[str, Any]) -> bool:
        """评估简单条件表达式"""
        # in 运算符：field in [1,2,3]
        match = re.match(r'(\w+)\s+in\s+\[([^\]]+)\]', condition)
        if match:
            field_name = match.group(1)
            values_str = match.group(2)
            field_value = context.get(field_name)

            if field_value is None:
                return False

            try:
                allowed_values = [int(v.strip()) for v in values_str.split(',')]
                return int(field_value) in allowed_values
            except ValueError:
                return False

        # range 运算符：field range [1,5]
        match = re.match(r'(\w+)\s+range\s+\[(\d+),(\d+)\]', condition)
        if match:
            field_name = match.group(1)
            start = int(match.group(2))
            end = int(match.group(3))
            field_value = context.get(field_name)

            if field_value is None:
                return False

            try:
                return start <= int(field_value) <= end
            except ValueError:
                return False

        # 比较运算符：field == value, field != value, field > value 等
        operators = ['==', '!=', '>=', '<=', '>', '<']
        for op in operators:
            if op in condition:
                parts = condition.split(op)
                if len(parts) == 2:
                    field_name = parts[0].strip()
                    expected_value_str = parts[1].strip()
                    field_value = context.get(field_name)

                    if field_value is None:
                        return False

                    try:
                        field_value = int(field_value)
                        expected_value = int(expected_value_str)

                        if op == '==':
                            return field_value == expected_value
                        elif op == '!=':
                            return field_value != expected_value
                        elif op == '>':
                            return field_value > expected_value
                        elif op == '<':
                            return field_value < expected_value
                        elif op == '>=':
                            return field_value >= expected_value
                        elif op == '<=':
                            return field_value <= expected_value
                    except ValueError:
                        return False

        # 无法解析的条件，返回False
        return False


# 全局实例
condition_evaluator = ConditionEvaluator()
